import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { CodeExample, PaginationResponse, QueryParams } from '@/types/admin'
import { api, API_ENDPOINTS } from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useCodeExampleStore = defineStore('codeExample', () => {
  // 状态
  const codeExamples = ref<CodeExample[]>([])
  const currentCodeExample = ref<CodeExample | null>(null)
  const pagination = ref({
    page: 1,
    limit: 20,
    total: 0,
    pages: 0
  })
  const isLoading = ref(false)
  const stats = ref({
    total: 0,
    runnable: 0,
    languages: [] as string[],
    stats: [] as any[]
  })

  // 获取代码示例列表
  const fetchCodeExamples = async (params: QueryParams = {}) => {
    try {
      isLoading.value = true
      
      // 构建查询参数
      const queryParams: any = {
        page: params.page || 1,
        limit: params.limit || 20,
        include: 'lesson'
      }
      
      // 添加其他查询参数
      if (params.search) queryParams.search = params.search
      if (params.language) queryParams.language = params.language
      if (params.isRunnable !== undefined) queryParams.isRunnable = params.isRunnable
      if (params.lessonId) queryParams.lessonId = params.lessonId
      if (params.orderBy) queryParams.orderBy = params.orderBy
      if (params.order) queryParams.order = params.order
      
      const response = await api.get<PaginationResponse<CodeExample>>(
        API_ENDPOINTS.CODE_EXAMPLES,
        queryParams
      )
      
      if (response.data?.data && response.data?.pagination) {
        codeExamples.value = response.data.data
        pagination.value = {
          page: response.data.pagination.page,
          limit: response.data.pagination.limit,
          total: response.data.pagination.total,
          pages: response.data.pagination.pages
        }
      }
      
    } catch (error) {
      console.error('获取代码示例列表失败:', error)
      ElMessage.error('获取代码示例列表失败')
      codeExamples.value = []
      pagination.value = {
        page: 1,
        limit: 20,
        total: 0,
        pages: 0
      }
    } finally {
      isLoading.value = false
    }
  }

  // 获取代码示例统计信息
  const fetchStats = async () => {
    try {
      const response = await api.get(API_ENDPOINTS.CODE_EXAMPLES_STATS)
      if (response.data?.data) {
        stats.value = response.data.data
      }
    } catch (error) {
      console.error('获取代码示例统计失败:', error)
      ElMessage.error('获取代码示例统计失败')
    }
  }

  // 获取代码示例详情
  const fetchCodeExampleById = async (id: number) => {
    try {
      isLoading.value = true
      const response = await api.get<CodeExample>(`${API_ENDPOINTS.CODE_EXAMPLES}/${id}`)
      if (response.data) {
        currentCodeExample.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取代码示例详情失败:', error)
      ElMessage.error('获取代码示例详情失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建代码示例
  const createCodeExample = async (codeExampleData: Partial<CodeExample>) => {
    try {
      const response = await api.post<CodeExample>(API_ENDPOINTS.CODE_EXAMPLES, codeExampleData)
      if (response.data) {
        codeExamples.value.unshift(response.data)
        ElMessage.success('代码示例创建成功')
        return response.data
      }
    } catch (error) {
      console.error('创建代码示例失败:', error)
      ElMessage.error('创建代码示例失败')
      throw error
    }
  }

  // 更新代码示例
  const updateCodeExample = async (id: number, codeExampleData: Partial<CodeExample>) => {
    try {
      const response = await api.put<CodeExample>(`${API_ENDPOINTS.CODE_EXAMPLES}/${id}`, codeExampleData)
      if (response.data) {
        const index = codeExamples.value.findIndex(c => c.id === id)
        if (index !== -1) {
          codeExamples.value[index] = response.data
        }
        if (currentCodeExample.value?.id === id) {
          currentCodeExample.value = response.data
        }
        ElMessage.success('代码示例更新成功')
        return response.data
      }
    } catch (error) {
      console.error('更新代码示例失败:', error)
      ElMessage.error('更新代码示例失败')
      throw error
    }
  }

  // 删除代码示例
  const deleteCodeExample = async (id: number) => {
    try {
      await api.delete(`${API_ENDPOINTS.CODE_EXAMPLES}/${id}`)
      codeExamples.value = codeExamples.value.filter(c => c.id !== id)
      if (currentCodeExample.value?.id === id) {
        currentCodeExample.value = null
      }
      ElMessage.success('代码示例删除成功')
    } catch (error) {
      console.error('删除代码示例失败:', error)
      ElMessage.error('删除代码示例失败')
      throw error
    }
  }

  // 批量删除代码示例
  const deleteCodeExamplesBatch = async (ids: number[]) => {
    try {
      await api.delete(API_ENDPOINTS.CODE_EXAMPLES_BATCH, { data: { ids } })
      codeExamples.value = codeExamples.value.filter(c => !ids.includes(c.id))
      ElMessage.success(`成功删除 ${ids.length} 个代码示例`)
    } catch (error) {
      console.error('批量删除代码示例失败:', error)
      ElMessage.error('批量删除代码示例失败')
      throw error
    }
  }

  // 清空当前代码示例
  const clearCurrentCodeExample = () => {
    currentCodeExample.value = null
  }

  // 重置状态
  const reset = () => {
    codeExamples.value = []
    currentCodeExample.value = null
    pagination.value = {
      page: 1,
      limit: 20,
      total: 0,
      pages: 0
    }
    isLoading.value = false
    stats.value = {
      total: 0,
      runnable: 0,
      languages: [],
      stats: []
    }
  }

  return {
    // 状态
    codeExamples,
    currentCodeExample,
    pagination,
    isLoading,
    stats,

    // 方法
    fetchCodeExamples,
    fetchStats,
    fetchCodeExampleById,
    createCodeExample,
    updateCodeExample,
    deleteCodeExample,
    deleteCodeExamplesBatch,
    clearCurrentCodeExample,
    reset
  }
}) 